<template>
  <div class="password login-card">
    <q-tabs
      v-model="loginTab"
      class="text-gray text-weight-medium narrow-indicator"
      no-caps dense inline-label
      align="center" style="width: 75.6%;margin: auto"
      :breakpoint="540"
      active-color="primary"
      indicator-color="primary"
    >
      <q-tab name="account" label="系统登录" class="text-size-24"/>
      <q-tab disable name="weixin" label="微信登录" />
    </q-tabs>
    <q-tab-panels v-model="loginTab" animated keep-alive class="mar-t-10 bg-transparent">
      <!--密码登录-->
      <q-tab-panel name="account">
        <q-form
          @submit="login"
        >
          <q-input rounded filled dense autofocus v-model="phone" label="手机号" lazy-rules mask="###########"
                   :rules="[val => val && val.length > 0 || '请填写手机号',
                        val => /^1[3456789]\d{9}$/.test(val) || '请填写正确的手机号']">
            <template v-slot:prepend>
              <q-icon name="iconfont icontubiao-1" style="color:#333;font-size: 18px" />
            </template>
          </q-input>
          <q-input rounded filled dense v-model="password" label="密码" lazy-rules type="password"
                   :rules="[val => val !== null && val !== '' || '请填写密码']" style="padding-bottom: 0">
            <template v-slot:prepend>
              <q-icon name="iconfont icontubiao-0" style="color:#333;font-size: 18px" />
            </template>
          </q-input>

          <div class="isRemember">
            <input class="aaa" type="checkbox" v-model="isRemember"/>记住密码
          </div>

          <div>
            <q-btn dense unelevated label="登录" class="full-width login-btn ma" style="margin-top: 0"
                   :loading="loginLoading" type="submit" color="primary"/>
          </div>
          <div class="link">
            <router-link to="/login/sure-phone" class="text-grey-10 link-txt">重置密码</router-link>
            <span @click="goCode" to="/login/code" class="text-grey-10 cursor-pointer link-txt">短信快捷登录</span>
          </div>
        </q-form>
      </q-tab-panel>
      <!--微信登录-->
      <q-tab-panel name="weixin">
        <img class="Q_code" src="statics/img/Q_code.png" alt="二维码">
        <p class="text-center margin-t-20">微信扫一扫登录</p>
      </q-tab-panel>
    </q-tab-panels>

    <!--版本更新进度显示对话框-->
    <!--FIXME 重构时应抽离成组件-->
    <q-dialog class="add-edit-process-define dialog" v-model="updateDialog" persistent>
      <q-card style="min-width: 400px;min-height: 100px;padding: 20px 10px">
        <div style="display: flex;justify-items: center;align-items: center;flex-direction: column">
          <div style="margin-bottom: 20px">
            <i class="iconfont icontubiao-76" style="color: #5F77FD"></i>
            <span>{{ ` 检测到新版本 , 正在下载 进度: ${percentage}%` }}</span>
          </div>
          <div class="progress-bar">
            <div class="progress-detail" :style="{width: `${percentage}%`}"></div>
          </div>
        </div>
      </q-card>
    </q-dialog>
    <login-company-dialog
    :show="isShowLoginCompanyDialog"
    @onLogin="onLogin"
    :loginParams="loginParams"
    @close="isShowLoginCompanyDialog = false; loginLoading = false"/>
  </div>
</template>

<script>
import { login, getCompnies } from 'src/boot/login/login'
import { saveToken, saveRefreshToken } from 'yz-help'
import { mapMutations, mapActions } from 'vuex'
import { savePassword, saveUserName, loadPassword, loadUserName } from 'src/assets/js/storage'
import loginCompanyDialog from './login-company-dialog'
import _ from 'lodash'

export default {
  name: 'password',
  data () {
    return {
      // account or weixin
      loginTab: 'account',
      // 手机号
      phone: null,
      isShowLoginCompanyDialog: false,
      loginParams: [],
      tid: '',
      // 密码
      password: null,
      loginLoading: false, // 登录的加载动画
      updateDialog: false, // 更新对话框
      percentage: 0, // 更新进度
      isRemember: true // 是否记住密码
    }
  },
  components: {
    loginCompanyDialog
  },
  created () {
    // 从缓存中获取记住的账号和密码
    this.getUserAndPassword()
  },
  /**
   *
   */
  methods: {
    onLogin (tid) {
      this.isShowLoginCompanyDialog = false
      this.rememberPassword(this.phone, this.password)
      // 记住账号和密码
      const params = {
        userName: this.phone,
        password: this.password,
        tid
      }
      this.loginLoading = true
      login(params).then((res) => {
        const token = res.data.token_type + ' ' + res.data.access_token
        const refreshToken = 'Bearer ' + res.data.refresh_token
        saveToken(token)
        saveRefreshToken(refreshToken)
        this.setToken(token)
        this.setRefreshToken(refreshToken)
        // this.$router.push('/main/home')
        this.$router.push('/main')
        window.location.href = '#/main'
      }).finally(() => {
        this.loginLoading = false
      })
    },
    // 手机号密码登录
    async login () {
      this.loginLoading = true
      try {
        let ret = await getCompnies(this.phone)
        if (ret.success) {
          const member = ret.data
          if (member.length === 1) {
            const tid = _.get(member[0], 'tid', '')
            this.onLogin(tid)
          } else {
            this.loginParams = member.map(v => {
              const item = v
              item.value = v.tid
              item.label = v.companyName
              return v
            })
            this.isShowLoginCompanyDialog = true
          }
        }
      } catch {
        this.loginLoading = false
      }
    },
    goCode () {
      if (!this.phone) {
        this.$router.push({
          path: '/login/code'
        })
      } else {
        this.$router.push({
          path: '/login/code',
          query: { phone: this.phone }
        })
      }
    },

    /**
     * 记住账号密码
     * @param {string} userName
     * @param {string} password
     */
    rememberPassword (userName, password) {
      try {
        let userNameNew = null
        let passwordNew = null
        this.isRemember ? userNameNew = userName : userNameNew = null
        this.isRemember ? passwordNew = password : passwordNew = null
        saveUserName(userNameNew)
        savePassword(passwordNew)
      } catch (e) {
        console.log(e)
      }
    },

    /**
     * 从缓存中获取账号和密码
     */
    getUserAndPassword () {
      try {
        loadUserName() ? this.phone = loadUserName() : this.phone = null
        loadPassword() ? this.password = loadPassword() : this.password = null
      } catch (e) {
        console(e)
      }
    },
    ...mapActions([
      'getWebScoket'
    ]),

    ...mapMutations({
      'setToken': 'SET_TOKEN',
      'setRefreshToken': 'SET_REFRESHTOKEN'
    })
  }
}
</script>

<style scoped lang="stylus">
  .login-card{
    width 100%
    .Q_code{
      width 163px
      height 163px
      display block
      margin 0 auto
    }
  }
  .progress-bar {
    width 100%
    height 14px
    background-color #d3d3d3
    border-radius 4px
    position relative
    margin-top 5px

    .progress-detail {
      height inherit
      background-color $secondary /* 不支持线性的时候显示 */
      background-image linear-gradient(to right, $secondary, #51a8e1, $primary);
      border-radius inherit
    }
  }
  .isRemember {
    height 40px
    display flex
    align-items center
    justify-content left
  }
  .isRemember input {
    margin-right 5px
  }
</style>
